<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>视频解析服务 - 配置管理</title>
    <link href="/static/bootstrap5/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .config-section {
            margin-bottom: 2rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #eee;
        }
        .form-group {
            margin-bottom: 1rem;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary mb-4">
        <div class="container">
            <a class="navbar-brand" href="/">视频解析服务</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item"><a class="nav-link" href="/">服务状态</a></li>
                    <li class="nav-item"><a class="nav-link" href="/parse-test">解析测试</a></li>
                    <li class="nav-item"><a class="nav-link" href="/user-manage">用户管理</a></li>
                    <li class="nav-item"><a class="nav-link" href="/ip-blacklist">IP黑名单</a></li>
                    <li class="nav-item"><a class="nav-link active" href="/config-manage">配置管理</a></li>
                </ul>
                <ul class="navbar-nav">
                    <li class="nav-item d-none" id="userInfoNav"><span class="nav-link" id="userInfo"></span></li>
                    <li class="nav-item">
                        <button class="btn btn-outline-light btn-sm" id="logoutBtn">退出登录</button>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- 配置管理内容 -->
    <div class="container">
        <div class="row mb-4">
            <div class="col">
                <h4>系统配置管理 <span class="text-muted">(仅管理员可见)</span></h4>
            </div>
        </div>

        <div class="card shadow">
            <div class="card-header bg-light d-flex justify-content-between align-items-center">
                <h5 class="mb-0">系统配置</h5>
                <button class="btn btn-primary" id="saveConfigBtn">保存配置</button>
            </div>
            <div class="card-body">
                <div class="alert alert-success d-none" id="saveSuccessAlert" role="alert"></div>
                <div class="alert alert-danger d-none" id="saveErrorAlert" role="alert"></div>

                <form id="configForm">
                    <!-- 系统基本配置 -->
                    <div class="config-section">
                        <h5>基本信息配置</h5>
                        <div class="row">
                            <div class="col-md-6 form-group">
                                <label for="app_name" class="form-label">应用名称</label>
                                <input type="text" class="form-control system-config" id="app_name" data-key="app_name">
                            </div>
                            <div class="col-md-6 form-group">
                                <label for="home_notice" class="form-label">首页公告</label>
                                <input type="text" class="form-control system-config" id="home_notice" data-key="home_notice">
                            </div>
                            <div class="col-md-6 form-group">
                                <label for="share_title" class="form-label">分享标题</label>
                                <input type="text" class="form-control system-config" id="share_title" data-key="share_title">
                            </div>
                            <div class="col-md-6 form-group">
                                <label for="share_imageUrl" class="form-label">分享图片URL</label>
                                <input type="text" class="form-control system-config" id="share_imageUrl" data-key="share_imageUrl">
                            </div>
                            <div class="col-md-12 form-group">
                                <label for="banner_imageUrl" class="form-label">Banner图片URL（多个用逗号分隔）</label>
                                <input type="text" class="form-control system-config" id="banner_imageUrl" data-key="banner_imageUrl">
                            </div>
                        </div>
                    </div>

                    <!-- 提示信息配置 -->
                    <div class="config-section">
                        <h5>提示信息配置</h5>
                        <div class="row">
                            <div class="col-md-6 form-group">
                                <label for="analysis_text" class="form-label">解析成功提示</label>
                                <input type="text" class="form-control system-config" id="analysis_text" data-key="analysis_text">
                            </div>
                            <div class="col-md-6 form-group">
                                <label for="save_text" class="form-label">保存成功提示</label>
                                <input type="text" class="form-control system-config" id="save_text" data-key="save_text">
                            </div>
                            <div class="col-md-6 form-group">
                                <label for="downloadErrorMsg" class="form-label">下载失败提示</label>
                                <input type="text" class="form-control system-config" id="downloadErrorMsg" data-key="downloadErrorMsg">
                            </div>
                            <div class="col-md-6 form-group">
                                <label for="rewardedVideoAdTips" class="form-label">视频广告提示</label>
                                <input type="text" class="form-control system-config" id="rewardedVideoAdTips" data-key="rewardedVideoAdTips">
                            </div>
                        </div>
                    </div>

                    <!-- API配置 -->
                    <div class="config-section">
                        <h5>API配置</h5>
                        <div class="row">
                            <div class="col-md-6 form-group">
                                <label for="Api" class="form-label">解析API地址</label>
                                <input type="text" class="form-control api-config" id="Api" data-key="Api">
                            </div>
                            <div class="col-md-6 form-group">
                                <label for="Api_code" class="form-label">API成功状态码</label>
                                <input type="number" class="form-control api-config" id="Api_code" data-key="Api_code">
                            </div>
                            <div class="col-md-6 form-group">
                                <label for="Down_Api" class="form-label">视频下载API</label>
                                <input type="text" class="form-control api-config" id="Down_Api" data-key="Down_Api">
                            </div>
                            <div class="col-md-6 form-group">
                                <label for="Down_pic" class="form-label">图片下载API</label>
                                <input type="text" class="form-control api-config" id="Down_pic" data-key="Down_pic">
                            </div>
                            <div class="col-md-6 form-group">
                                <label for="clientId" class="form-label">客户端ID</label>
                                <input type="text" class="form-control api-config" id="clientId" data-key="clientId">
                            </div>
                            <div class="col-md-6 form-group">
                                <label for="clientSecretKey" class="form-label">客户端密钥</label>
                                <input type="text" class="form-control api-config" id="clientSecretKey" data-key="clientSecretKey">
                            </div>
                        </div>
                    </div>

                    <!-- 其他配置 -->
                    <div class="config-section">
                        <h5>其他配置</h5>
                        <div class="row">
                            <div class="col-md-6 form-group">
                                <label for="videoAD_ID" class="form-label">视频广告ID</label>
                                <input type="text" class="form-control system-config" id="videoAD_ID" data-key="videoAD_ID">
                            </div>
                            <div class="col-md-6 form-group">
                                <label for="BannerAD_ID" class="form-label">Banner广告ID</label>
                                <input type="text" class="form-control system-config" id="BannerAD_ID" data-key="BannerAD_ID">
                            </div>
                            <div class="col-md-6 form-group">
                                <label for="index_video_ad" class="form-label">首页视频广告</label>
                                <input type="text" class="form-control system-config" id="index_video_ad" data-key="index_video_ad">
                            </div>
                            <div class="col-md-6 form-group">
                                <label for="mytext" class="form-label">缓存时间（秒）</label>
                                <input type="number" class="form-control system-config" id="mytext" data-key="mytext">
                            </div>
                            <div class="col-md-12 form-group">
                                <label for="foot_text" class="form-label">页脚文本</label>
                                <textarea class="form-control system-config" id="foot_text" data-key="foot_text" rows="3"></textarea>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="/static/bootstrap5/js/bootstrap.bundle.min.js"></script>
    <script>
        // 1. 权限验证（仅管理员可访问）
        async function checkAdminAuth() {
            const token = localStorage.getItem('access_token');
            if (!token) {
                window.location.href = '/login';
                return;
            }

            try {
                const response = await fetch('/users/me', {
                    headers: { 'Authorization': `Bearer ${token}` }
                });
                
                if (!response.ok) {
                    throw new Error('Token无效');
                }
                
                const user = await response.json();

                if (!user.is_admin) {
                    // 非管理员，跳首页
                    window.location.href = '/';
                } else {
                    // 管理员：显示用户信息和加载配置
                    document.getElementById('userInfo').textContent = `当前用户：${user.username}（管理员）`;
                    document.getElementById('userInfoNav').classList.remove('d-none');
                    loadConfigData(token);
                }
            } catch (err) {
                localStorage.removeItem('access_token');
                window.location.href = '/login';
            }
        }

        // 2. 加载配置数据
        async function loadConfigData(token) {
            try {
                const response = await fetch('/api/config/get', {
                    headers: { 'Authorization': `Bearer ${token}` }
                });
                
                if (!response.ok) {
                    throw new Error('获取配置失败');
                }
                
                const configData = await response.json();
                
                // 填充系统配置
                const systemConfig = configData.system_config || {};
                document.querySelectorAll('.system-config').forEach(input => {
                    const key = input.getAttribute('data-key');
                    if (systemConfig[key] !== undefined) {
                        input.value = systemConfig[key];
                    }
                });
                
                // 填充API配置
                const apiConfig = configData.api_config || {};
                document.querySelectorAll('.api-config').forEach(input => {
                    const key = input.getAttribute('data-key');
                    if (apiConfig[key] !== undefined) {
                        input.value = apiConfig[key];
                    }
                });
                
            } catch (err) {
                console.error('加载配置失败：', err);
                alert(`加载配置失败: ${err.message}`);
            }
        }

        // 3. 保存配置
        document.getElementById('saveConfigBtn').addEventListener('click', async () => {
            const token = localStorage.getItem('access_token');
            const successAlert = document.getElementById('saveSuccessAlert');
            const errorAlert = document.getElementById('saveErrorAlert');
            successAlert.classList.add('d-none');
            errorAlert.classList.add('d-none');

            try {
                // 收集系统配置
                const systemConfig = {};
                document.querySelectorAll('.system-config').forEach(input => {
                    const key = input.getAttribute('data-key');
                    systemConfig[key] = input.value;
                });
                
                // 收集API配置
                const apiConfig = {};
                document.querySelectorAll('.api-config').forEach(input => {
                    const key = input.getAttribute('data-key');
                    apiConfig[key] = input.value;
                });
                
                // 提交保存
                const response = await fetch('/api/config/update', {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify({
                        system_config: systemConfig,
                        api_config: apiConfig
                    })
                });
                
                if (!response.ok) {
                    throw new Error('保存配置失败');
                }
                
                const result = await response.json();
                successAlert.textContent = result.msg || '配置保存成功！';
                successAlert.classList.remove('d-none');
                
                // 3秒后隐藏成功提示
                setTimeout(() => {
                    successAlert.classList.add('d-none');
                }, 3000);
                
            } catch (err) {
                errorAlert.textContent = `保存失败：${err.message}`;
                errorAlert.classList.remove('d-none');
            }
        });

        // 4. 退出登录
        document.getElementById('logoutBtn').addEventListener('click', () => {
            localStorage.removeItem('access_token');
            window.location.href = '/login';
        });

        // 页面加载时验证权限
        checkAdminAuth();
    </script>
</body>
</html>
    